package com.lahuan.config.datasouce;


import com.lahuan.config.datasouce.entity.GlobalTransactionState;
import com.lahuan.config.datasouce.entity.GlobalXid;
import com.lahuan.config.datasouce.entity.TransactionBranch;

import java.util.HashSet;

/**
 * @author lfy
 */
public class CustomTransactionHolder {

    /**
     * 当前线程的事务的xid
     */
    private static final ThreadLocal<GlobalXid> globalXidHolder = new ThreadLocal<>();
    /**
     * 当前线程一共用到的分支
     */
    private static final ThreadLocal<HashSet<TransactionBranch>> transactionBranchSetHolder = new ThreadLocal<>();
    /**
     * 当前全局事务是否出现异常
     */
    private static final ThreadLocal< Object> transactionException = new ThreadLocal<>();
    /**
     * 当前线程在用的分支
     */
    private static final ThreadLocal<TransactionBranch> currentTransactionBranch = new ThreadLocal<>();
    /**
     * 当前全局事务的状态
     */
    private static final ThreadLocal<GlobalTransactionState> transactionStateHolder = new ThreadLocal<>();

    protected static void clear(){
        globalXidHolder.remove();
        transactionBranchSetHolder.remove();
        transactionException.remove();
        transactionStateHolder.remove();
        currentTransactionBranch.remove();
    }
    public static  GlobalTransactionState getGlobalTransactionState(){
        GlobalTransactionState state = transactionStateHolder.get();
        if(state==null){
            return GlobalTransactionState.none;
        }
        return state;
    }
    public static TransactionBranch getCurrentTransactionBranch(){
        return currentTransactionBranch.get();
    }
    public static void  setCurrentTransactionBranch(TransactionBranch branch){
        currentTransactionBranch.set(branch);
    }
    public static void setGlobalTransactionState(GlobalTransactionState state){
        transactionStateHolder.set(state);
    }

    public static GlobalXid getGlobalXid() {
        return globalXidHolder.get();
    }

    public static void setGlobalXid(GlobalXid globalXid) {
        globalXidHolder.set(globalXid);
    }

    public static HashSet<TransactionBranch> getTransactionBranchSet() {
        return transactionBranchSetHolder.get();
    }

    public static void addTransactionBranchSet(TransactionBranch transactionBranch) {
        HashSet<TransactionBranch> set = transactionBranchSetHolder.get();
        if(set ==null){
            set = new HashSet<>();
            transactionBranchSetHolder.set(set);
        }
        set.add(transactionBranch);
    }


    public static void setTransactionException() {
        transactionException.set("error");
    }

    public static boolean getTransactionException() {
        return transactionException.get() !=null ;
    }
}
